	import navBar from '../common/Navbar/navbar.vue'
	import { openTable, getTableState, getList,clearOrder,getMoreNorm,getDishDetail, getDishList, addDish, delDish, getTableOrderDishList } from '../api/api.js'
	import initWebScoket from '../../utils/webscoket'
	import {mapState, mapMutations, mapActions} from 'vuex'
	export default {
		data() {
			return {
				title: 'Hello',
				openOrderCartList: false,
				typeListData: [],
				dishListData: [],
				dishListItems: [],
				dishDetailes: {},
				openDetailPop: false,
				openMoreNormPop: false,
				moreNormDataes: null,
				tableInfo:null,
				moreNormDishdata:null,
				moreNormdata:null,
				dishMealData:null,
				openTablePeoPleNumber: 1,
				reservedState:false,
				orderData: 0,
				typeIndex: 0,
				openTablePop: false,
				flavorDataes: [],
				orderDishNumber: 0,
				orderDishPrice: 0,
				showInfo:{
					title: "该餐桌已被预定",
					desc: "请联系服务员更换其他餐桌",
					but: "知道了"
				},
				params:{
					shopId: 'f3deb',
					storeId: '1282344676983062530',
					tableId: '1282346960773238786'
				  },
			}
		},
		computed:{
			orderListDataes:function() {
				return this.orderListData().dishList
			},
			loaddingSt:function() {
				return this.lodding()
			},
			orderAndUserInfo:function() {
				let orderData = []
				Array.isArray(this.orderListDataes) && this.orderListDataes.forEach((n,i) => {
					let userData = {}
					userData.nickName = n.nickName ?? ''
					userData.avatarUrl = n.avatarUrl ?? ''
					userData.dishList = [n]
					const num = orderData.findIndex(o => o.nickName == userData.nickName)
					if (num != -1){
						orderData[num].dishList.push(n)
					} else {
						orderData.push(userData)
					}
				})
				return orderData
			},
			getDishAdd:function() {
				return this.$store.state.orderListData
			},
		},
		watch:{
			// 监听websock 数据接收
			getDishAdd:function(){
				this.computOrderInfo()
				this.setOrderNum()
			}
		},
		components: { navBar },
		onLoad() {
			uni.onNetworkStatusChange(function(res) {
				if (res.isConnected == false) {
					uni.navigateTo({url: '/pages/nonet/index'})
				} 
			})
			this.init()
			this.setStoreInfo(this.params)
		},
		methods: {
			...mapMutations(['setShopInfo', 'initdishListMut', 'setStoreInfo', 'setBaseUserInfo', 'setLodding']),
			...mapState(['shopInfo', 'orderListData', 'baseUserInfo', 'lodding']),
			getData(){
				let res=wx.getMenuButtonBoundingClientRect()
				let _this = this
				this.selectHeight = res.height
				uni.showModal({
					title: '温馨提示',
					content: '亲，授权微信登录后才能正点餐！',
					showCancel: false,
					success(res) {
						if (res.confirm) {
							uni.getUserProfile({
								desc: '登录',
								success(userInfo) {
									_this.setBaseUserInfo(userInfo.rawData)
								},
								fail:function(err){
								   // uni.showToast({title: "授权失败", icon: 'error',})
								   _this.showInfo = {
									   title: "授权失败",
									   desc: "请重新授权后点餐",
									   but: "知道了"
								   }
								   _this.reservedState = true
								   console.log("获取失败: ",err)
								}
							})
						}
					}
				})
			}, 
			
			// 初始化数据
			async init(){
				// 获取用户信息 
				// 扫码进入
				let params = {}
				// 二维码链接内容会以参数q的形式带给页面，在onLoad事件中提取q参数并自行decodeURIComponent一次，即可获取原二维码的完整内容。
				// 格式一：https://canzg-wsl.itheima.net/miniprogram/?shopId=f3deb&storeId=1282344676983062530&tableId=1282346960773238786
				// q = 'https%3a%2f%2fcanzg-wsl.itheima.net%2fminiprogram%2f%3fshopId%3df3deb%26storeId%3d1282344676983062530%26tableId%3d1282346960773238786'
				// 格式二：https://canzg-wsl.itheima.net/miniprogram/f3deb/1282344676983062530/1282346960773238786
				// q = 'https%3a%2f%2fcanzg-wsl.itheima.net%2fminiprogram%2ff3deb%2f1282344676983062530%2f1282346960773238786'
				if (this.$router && this.$router.params.q) {
				  let q = this.$router.params.q
				  q = decodeURIComponent(q)
				  // 格式一
				  let arr = q.split('?')[1].split('&')
				  for (let i = 0; i < arr.length; i++) {
					let temp = arr[i].split('=')
					params[temp[0]] = temp[1]
				  }
				  // 格式二
				  // let arr = q.split('/')
				  // params['shopId'] = arr[arr.length - 3]
				  // params['storeId'] = arr[arr.length - 2]
				  // params['tableId'] = arr[arr.length - 1]
				  this.params = params
				}
				// 获取作台初始数据
			    await getTableState(this.params).then(res => {
					this.tableInfo = res.data
					this.setShopInfo(res.data)
					// 如果为开桌,打开开桌流程 （开启开桌弹窗） 开桌则初始化websocket结收购物车信息，首次需要手动获取订单列表
					if(!res.data.opened){
						this.openTablePop = true
					} else {
						this.getData()
						initWebScoket(this.params)
						this.getTableOrderDishListes()
					}
				}).catch(err => {
					this.reservedState = true;
				})
				// 获取菜品分类列表和 第一个分类下的菜品
				await getList(this.params).then(res => {
					this.typeListData = res.data
					if (res.data.length > 0){
						this.getDishListDataes(res.data[0])
					}
				}).catch(err => {
					console.log(err)
				})
			},
			// 开桌操作 开桌后初始化websocket结束点餐信息
			async openTableHandle(){
				openTable({tableId: this.params.tableId, seatNumber: this.openTablePeoPleNumber}).then(res => {
					this.openTablePop = false
					initWebScoket(this.params)
					this.getTableOrderDishListes()
					// this.computOrderInfo()
				}).catch(err => {
					console.log(err)
				})
			},
			// 获取菜品列表
			async getDishListDataes(params, index){
				const param = {categoryId:params.categoryId,type: params.type, page: 1, pageSize: 1000}
				await getDishList(param).then(res => {
				    this.dishListData = res.data.items
					this.typeIndex = index
					this.setOrderNum()
				}).catch(err => {
					console.log(err)
				})
			},
			// 获取购物车订单列表
			async getTableOrderDishListes(){
				await getTableOrderDishList(this.params).then(res => {
					this.initdishListMut(res.data)
					// this.computOrderInfo()
				}).catch(err => {
					console.log(err)
				})
			},
			// 去订单页面
			goOrder(){
				uni.navigateTo({url: '/pages/order/index'})
			},
			// 加菜 - 添加菜品
			async addDishAction(item){
				if(!this.orderListDataes.some(n => n.id == item.dishId) && this.flavorDataes.length > 0) {
					item.flavorRemark = JSON.stringify(this.flavorDataes)
				}
				const wxUserInfo = this.baseUserInfo()
				await addDish({...item,...wxUserInfo,dishId:item.dishId ?? item.id,dishName:item.dishName ?? item.name, dishNumber: 1, tableId: this.params.tableId}).then(res => {
					// this.computOrderInfo()
					// this.setOrderNum()
				}).catch(err => {
					uni.showToast({
						title: err,
						icon: 'none',
					})
				})
			},
			// 减菜 - 添加菜品
			async redDishAction(item){
				await delDish({dishId:item.dishId ?? item.id,tableId: this.params.tableId}).then(res => {
					// this.computOrderInfo()
					// this.setOrderNum()
				}).catch(err => {
					uni.showToast({
						title: err,
						icon: 'none',
					})
				})
			},
			//清空购物车
			clearCardOrder(){
				clearOrder({tableId: this.params.tableId}).then(res => {
					// this.computOrderInfo()
					// this.setOrderNum()
					this.openOrderCartList = false
				}).catch(err => {
					uni.showToast({
						title: err,
						icon: 'none',
					})
				})
			},
			// 打开菜品牌详情
			openDetailHandle(item){
				this.dishDetailes = item
				if(item.type == 2){
					getDishDetail({setmealId:item.dishId}).then(res => {
						this.openDetailPop = true
						this.dishMealData= res.data
					}).catch(err => {
						uni.showToast({title: err.message,icon: 'error',})
						console.log(err)
					})
				} else {
					this.openDetailPop = true
				}  
			},
			// 多规格数据处理
			moreNormDataesHandle(item){
				this.moreNormDishdata = item
				getMoreNorm({dishId: item.dishId}).then(res => {
					this.openMoreNormPop = true
					this.moreNormdata = res.data
				}).catch(err => {
					uni.showToast({title: err.message,icon: 'error',})
					console.log(err)
				})
				
			},
			// 选规格 处理一行只能选择一种 
			checkMoreNormPop(obj,item){
				let ind
				let findst = obj.some(n => {
					ind = this.flavorDataes.findIndex(o => o == n) 
					return ind != -1
				})
				const num = this.flavorDataes.findIndex(it => it == item)
				if (num == -1 && !findst){
					this.flavorDataes.push(item)
				} else if(findst) {
					this.flavorDataes.splice(ind, 1)
					this.flavorDataes.push(item)
				} else {
					this.flavorDataes.splice(num, 1)
				}
			},
			// 关闭选规格弹窗
			closeMoreNorm(moreNormDishdata){
				this.flavorDataes.splice(0, this.flavorDataes.length)
				this.openMoreNormPop = false
			},
			// 设置开桌人数
			setOpenTableNumber(st){
				if(st == 'add'){
					this.openTablePeoPleNumber+=1
				} else {
					this.openTablePeoPleNumber =  this.openTablePeoPleNumber > 1 ? this.openTablePeoPleNumber-1 : 1
				}
			},
			// 详情页面选规格
			detailCheckNorm(dishDetailes) {
				this.openDetailPop = false; 
				this.moreNormDataesHandle(dishDetailes)
			},
			// 订单里和总订单价格计算
			computOrderInfo(){
				let oriData = this.orderListDataes
				this.orderDishNumber = this.orderDishPrice = 0;
				oriData.map((n,i) => {
					this.orderDishNumber += n.number
					this.orderDishPrice += n.number * n.price
				})
			},
			// 处理点餐数量 - 更新菜品已点餐数量
			setOrderNum(){
				let ODate = this.dishListData
				let CData = this.orderListDataes
				ODate && ODate.map((obj, index) => {
					obj.dishNumber = 0
					CData && CData.forEach((tg, ind) => {
						if (obj.dishId == tg.id){
							obj.dishNumber = tg.number
							obj.flavorRemark = tg.flavorRemark
						}
					})
				})
				if(this.dishListItems.length == 0){
					this.dishListItems = ODate
				} else {
					this.dishListItems.splice(0, this.dishListItems.length, ...ODate)
				}
			}
		}
	}